package com.loongtech.bi.action.biflow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.core.util.Time;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * ClassName: AccountInfoFlowNewAction
 * 
 * @Description: 账号信息流水
 * @author liuchen
 * @date 2017-5-17 下午5:18:51
 */
@Controller
@Scope("prototype")
@RequestMapping("/flow/accountInfoFlow")
public class AccountInfoFlowNewAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	HadoopQueryManager hadoopQueryManager;

	@RequestMapping(value = "updateServer.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateServer(HttpServletRequest request, HttpServletResponse response, String serverid, String callback) {
		try {
			queryServer = serverid;
			selectServerItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updateChannel.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateChannel(HttpServletRequest request, HttpServletResponse response, String channelid,
			String callback) {
		try {
			queryChannel = channelid;
			selectChannelItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updatePlatform.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updatePlatform(HttpServletRequest request, HttpServletResponse response, String platformid,
			String callback) {
		try {
			queryPlatform = platformid;
			selectPlatformItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	/**
	 * 
	 * @Description: TODO 获取参数
	 * @param @param request
	 * @param @param response
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String params,
			String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> m = jsonToMap(params);
			Date dateEnd = Time.formatDate((String) m.get("dateEnd"), "yyyy-MM-dd");

			String userid = (String) m.get("userid");
			String roleid = (String) m.get("roleid");
			String rolename = (String) m.get("rolename");

			String platform = (String) m.get("platform");
			String channel = (String) m.get("channel");
			String serverid = (String) m.get("serverid");

			// 用户ID，角色ID必要有一个非空
            if (StringUtils.isBlank(userid) && StringUtils.isBlank(roleid) && StringUtils.isBlank(rolename)) {
				result.put("res", "1");
				result.put("msg", "用户ID，角色ID, 角色名必须至少有一个非空!");
				printToJson(response, result, callback);
				return;
			}

			if (HadoopQueryManager.VISIT_QUEUE.offer("AccountInfoFlowNewAction")) {
				System.out.println("VISIT_QUEUE offer AccountInfoFlowNewAction ok!");

				StringBuffer sql = new StringBuffer();
				sql.append("select a.logtime,b.updatetime ,a.platform,a.channel,a.serverid,a.userid,a.roleid,a.rolename,a.occupation,a.gender,b.afterlevel,b.viplevel,a.mac from (select logtime,platform,channel,serverid,userid,roleid,rolename,occupation,gender,mac from rolecreate where 1=1 ");
				if (!StringUtils.isBlank(userid)) {
					StringBuilder sb = new StringBuilder();
					StringTokenizer st = new StringTokenizer(userid.trim());

					int index = 0;

					while (st.hasMoreTokens()) {
						if (index == 0) {
							sb.append("'").append(st.nextToken()).append("'");
						} else {
							sb.append(",'").append(st.nextToken()).append("'");
						}

						index++;
					}

					sql.append(" and userid in (");
					sql.append(sb.toString());
					sql.append(") ");
				}

				if (!StringUtils.isBlank(roleid)) {
					StringBuilder sb = new StringBuilder();
					StringTokenizer st = new StringTokenizer(roleid.trim());

					int index = 0;

					while (st.hasMoreTokens()) {
						if (index == 0) {
							sb.append("'").append(st.nextToken()).append("'");
						} else {
							sb.append(",'").append(st.nextToken()).append("'");
						}

						index++;
					}

					sql.append(" and cast(roleid as string) in (");
					sql.append(sb.toString());
					sql.append(") ");
				}
				if (!"0".equals(platform)) {
					sql.append(" and platform = ");
					sql.append(platform);
				}
				if (!"0".equals(channel)) {
					sql.append(" and channel = '");
					sql.append(channel);
					sql.append("' ");
				}
				if (!"0".equals(serverid)) {
					sql.append(" and serverid = ");
					sql.append(serverid);
				}
				if (!StringUtils.isBlank(rolename)) {
					StringBuilder sb = new StringBuilder();
					StringTokenizer st = new StringTokenizer(rolename.trim());

					int index = 0;

					while (st.hasMoreTokens()) {
						if (index == 0) {
							sb.append("'").append(st.nextToken()).append("'");
						} else {
							sb.append(",").append("'").append(st.nextToken()).append("'");
						}

						index++;
					}

					sql.append(" and rolename in (");
					sql.append(sb.toString());
					sql.append(") ");
				}

				sql.append(" ) as a left join (select updatetime,userid,roleid,afterlevel,viplevel from totalrolelevelup where dt = '"
						+ Time.getDateStr(dateEnd)
						+ "') as b on a.userid = b.userid and a.roleid = b.roleid order by a.logtime asc");

				Entry<List<String>, List<Object[]>> ret = hadoopQueryManager.executeSQL(sql.toString());
				if (null == ret || null == ret.getKey() || ret.getKey().isEmpty() || null == ret.getValue()) {
                    result.put("res", new ArrayList<Object[]>());
                    result.put("data", "");
                    printToJson(response, result, callback);
					return;
				}

				List<Object[]> lo = ret.getValue();

				for (Object[] o : lo) {
					o[2] = BiPlatformManager.getPlatformNameById((String) o[2]);
					o[3] = BiPlatformManager.getChannelNameById((String) o[3]);
					o[4] = BiPlatformManager.getServerNameById((String) o[4]);
					o[8] = getSchoolNameById(o[8]) + "(" + o[8] + ")";
					o[9] = getGenderById(o[9]) + "(" + o[9] + ")";
				}

				result.put("res", "0");
				result.put("data", lo);
				printToJson(response, result, callback);
			} else {
				System.out.println("VISIT_QUEUE offer AccountInfoFlowNewAction failed!");
				result.put("res", "1");
				result.put("msg", "当前系统正被访问，为保证服务器稳定，请稍后再试!");
				printToJson(response, result, callback);
				return;
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	public String getSchoolNameById(Object id) {
		if (StringUtils.isBlank((String) id)) {
			return "";
		}

		return GameParamConfigManager.getItemsRevise(CommonGameParam.SCHOOL).get(String.valueOf(id)); // SchoolManager.getSchoolNameById(Integer.parseInt(String.valueOf(id)));
	}

	public String getGenderById(Object genderId) {
		String str = String.valueOf(genderId);
		Map<String, String> revise = GameParamConfigManager.getItemsRevise(CommonGameParam.ROLEGENDER);

		return revise == null || revise.get(str) == null ? str : revise.get(str);
	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	protected String csvContent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String csvFileName() {
		// TODO Auto-generated method stub
		return null;
	}
}
